<template>
  <el-container>
    <!-- 左侧 -->
    <el-aside width="200px">
      <el-menu :default-openeds="zkPath" @select="select">
        <el-submenu index="1">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>分组</span>
          </template>
          <el-menu-item-group>
            <el-menu-item :index="group" v-for="group of groups" :key="group">
              {{ group == "" ? "默认分组" : group }}
            </el-menu-item>
            <el-menu-item index="input" v-if="inputVisible">
              <el-input
                v-model="inputValue"
                ref="saveTagInput"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              ></el-input>
            </el-menu-item>
            <el-menu-item index="add" v-else @click="showInput">
              + New Group
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
        <el-menu-item index="2">
          <i class="el-icon-menu"></i>
          <span slot="title">自动订阅</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-document"></i>
          <span slot="title">最近阅读</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <!-- 右侧 -->
    <el-container>
      <!-- 头 -->
      <el-header> 头 </el-header>
      <!-- 主体 -->
      <el-main>
        <!-- 表格 -->
        <el-table
          ref="multipleTable"
          :data="bookRacks"
          max-height="1000"
          stripe
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="bookName" label="书名" fixed="left">
          </el-table-column>
          <el-table-column prop="lastChapterName" label="最新章节">
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间">
          </el-table-column>
          <el-table-column prop="writerName" label="作者"> </el-table-column>
          <el-table-column prop="readChapterIdTitle" label="阅读进度">
            <template slot-scope="scope">
              <div
                @click="
                  toChapter(scope.row.bookId, scope.row.readChapterId)
                "
              >
                {{ scope.row.readChapterIdTitle }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="chapter" label="未读章节"> </el-table-column>
          <el-table-column label="订阅状态">
            <template slot-scope="scope">
              <el-tag
                :type="
                  scope.row.subscribe === 'SIGNING' ? 'primary' : 'success'
                "
                disable-transitions
                >{{
                  scope.row.subscribe === "SIGNING" ? "已订阅" : "未订阅"
                }}</el-tag
              >
            </template>
          </el-table-column>
          <!-- 尾部操作选项 -->
          <el-table-column fixed="right">
            <!-- 表头 -->
            <template slot="header">
              <!-- slot-scope="scope" -->
              <!-- 移动按钮 -->
              <el-button
                type="info"
                plain
                size="mini"
                @click="dialogVisible = true"
                >移动至<i class="el-icon-top-right el-icon--right"></i
              ></el-button>
              <!-- 删除按钮 -->

              <template>
                <el-popconfirm
                  title="确定要将选中的书籍移除书架吗?"
                  @confirm="deleteData"
                >
                  <el-button
                    slot="reference"
                    type="danger"
                    plain
                    size="mini"
                    icon="el-icon-delete"
                  ></el-button>
                </el-popconfirm>
              </template>
            </template>
            <!-- 表格项 -->
            <template slot-scope="scope">
              <el-dropdown
                trigger="click"
                placement="bottom"
                @command="
                  (command) => {
                    actionTableItem(command, scope);
                  }
                "
              >
                <span class="el-dropdown-link">
                  <i class="el-icon-more"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="置顶">置顶</el-dropdown-item>
                  <el-dropdown-item command="移动至">移动至</el-dropdown-item>
                  <el-dropdown-item
                    command="订阅"
                    v-if="scope.row.subscribe == 'NOT_SIGNING'"
                    >订阅</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="取消订阅"
                    v-if="scope.row.subscribe == 'SIGNING'"
                    >取消订阅</el-dropdown-item
                  >
                  <el-dropdown-item command="删除">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 弹出框 -->
        <el-dialog
          title="分组"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          :show-close="false"
          width="30%"
        >
          <!-- 事件
        open	Dialog 打开的回调	—
        opened	Dialog 打开动画结束时的回调	—
        close	Dialog 关闭的回调	—
        closed	Dialog 关闭动画结束时的回调 - -->
          <template>
            <el-radio
              v-model="radio"
              v-for="group of groups"
              :key="group"
              :disabled="group == radio"
              :label="group"
              >{{ group == "" ? "默认分组" : group }}</el-radio
            >
          </template>
          <span slot="footer" class="dialog-footer">
            <el-button @click="unAffirmDialog">取 消</el-button>
            <el-button type="primary" @click="affirmDialog">确 定</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {
  selectBookRackList,
  selectGroups,
  moveBookRack,
  logicalDeletion,
  bookSort,
  subscribe,
  selectChapterObj,
} from "@/api";
export default {
  methods: {
    toChapter(bookId, chapterId) {
      //根据id查询sort
      console.log(bookId, chapterId);
      
      selectChapterObj(bookId, chapterId)
        .then(({ data }) => {
          this.$store.commit("routeJump/updateToChapterAction", {
            chapterSort: data.data.chapterOrder,
            bookId: bookId,
          });
        })
        .catch((err) => {});
    },
    deleteData() {
      if (this.multipleSelection.length > 0) {
        logicalDeletion(this.multipleSelection)
          .then(({ data }) => {
            if (data.code != null) {
              this.bookRacks = this.bookRacks.filter((x) => {
                return !this.multipleSelection.some((item) => {
                  return x.bookId === item;
                });
              });
            }
            console.log("删除成功");
          })
          .catch((err) => {});
      }
    },
    // 表格多选框
    selectionChange(selection) {
      console.log(`当选择项发生变化时会触发该事件${selection}`);
      console.log(selection);
      this.multipleSelection = selection.map((currentValue) => {
        return currentValue.bookId;
      });
      console.log(this.multipleSelection);
    },
    //对话框确认
    affirmDialog() {
      //TODO:将选中的表单项multipleSelection添加到选中的分组radio
      console.log(this.multipleSelection.length);
      if (this.multipleSelection.length > 0) {
        console.log(
          `将${this.multipleSelection}从--${this.pitchOn}f分组--移动到${this.radio}分组`
        );
        moveBookRack(this.pitchOn, this.radio, this.multipleSelection)
          .then(({ data }) => {
            this.bookRacks = this.bookRacks.filter((x) => {
              return !this.multipleSelection.some((item) => {
                return x.bookId === item;
              });
            });
            console.log("数据变化", this.bookRacks);
          })
          .catch((err) => {});
      }
      this.dialogVisible = false;
    },
    unAffirmDialog() {
      this.radio = this.pitchOn;
      this.dialogVisible = false;
    },
    // 操作具体表格项时
    //a选中的菜单项
    //b表单项数据
    actionTableItem(command, scope) {
      //TODO:根据command判断对scope作不同的操作
      let ve = this;
      console.log("动作", command);
      console.log("scope：", scope);
      this.multipleSelection = [scope.row.bookId];
      console.log("multipleSelection", this.multipleSelection);
      if (command == "移动至") {
        this.dialogVisible = true;
      } else if (command == "删除") {
        logicalDeletion(this.multipleSelection)
          .then(({ data }) => {
            if (data.code != null) {
              this.bookRacks = this.bookRacks.filter((x) => {
                return !this.multipleSelection.some((item) => {
                  return x.bookId === item;
                });
              });
            }
            console.log("删除成功");
          })
          .catch((err) => {});
      } else if (command == "置顶") {
        let ite;
        let arr = this.bookRacks.filter((x) => {
          return !this.multipleSelection.some((item) => {
            if (x.bookId === item) {
              ite = x;
              return true;
            } else {
              return false;
            }
          });
        });
        let arra = arr.map((a) => {
          return a.bookId;
        });
        arra.unshift(this.multipleSelection[0]);
        console.log("ite", ite);
        arr.unshift(ite);
        bookSort(this.pitchOn, arra)
          .then(({ data }) => {
            this.bookRacks = arr;
            console.log("成功置顶并排序");
          })
          .catch((err) => {});
      } else if (command == "取消订阅") {
        console.log("-----取消订阅");
        subscribe(this.multipleSelection[0])
          .then(({ data }) => {
            console.log("-----取消订阅");
            this.aj(
              "NOT_SIGNING",
              "取消订阅完成",
              this.multipleSelection[0],
              scope.row
            );
          })
          .catch((err) => {});
      } else if (command == "订阅") {
        console.log("-----订阅");
        subscribe(scope.row.bookId)
          .then(({ data }) => {
            console.log("-----订阅");

            this.aj(
              "SIGNING",
              "订阅完成",
              this.multipleSelection[0],
              scope.row
            );
          })
          .catch((err) => {});
      }
    },
    aj(state, message, bookId, row) {
      let d;
      console.log(this.bookRacks.length);
      for (let index = 0; index < this.bookRacks.length; index++) {
        console.log(this.bookRacks[index].bookId);
        if (this.bookRacks[index].bookId == bookId) {
          console.log("ijj");
          d = index;
          break;
        }
      }

      console.log("----订阅");
      row.subscribe = state;
      this.bookRacks.splice(d, 1, row);
      this.$message({
        message: message,
        type: "success",
      });
    },
    //左侧导航菜单激活回调
    select(index, indexPath) {
      this.zkPath = indexPath;
      //TODO:更新表格中的数据
      if (indexPath[0] == 1 && this.pitchOn != indexPath[1]) {
        if (indexPath[1] == "add") {
          return;
        }
        console.log(indexPath);
        this.pitchOn = indexPath[1];
        this.radio = indexPath[1];
        selectBookRackList(indexPath[1])
          .then(({ data }) => {
            this.bookRacks = data.data;
            console.log("书籍信息", data);
          })
          .catch((err) => {});
      }
    },
    //显示input，使input获取焦点
    showInput() {
      this.inputVisible = true;
      //在下次更新数据时,获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //输入完成后修改groups数据，恢复初始状态，vue重新加载数据
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.groups.push(inputValue);
        //TODO:保存到远程数据库
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 获取表格数据
    getBookList(userId, group) {
      //TODO:获取数据
      //this.tableData =
    },
  },
  data() {
    return {
      pitchOn: "",
      zkPath: [1, ""],
      inputVisible: false,
      inputValue: "",
      // 所有分组，查询得知
      groups: ["默认分组", "玄幻", "白金"],
      //在对话框选中的分组
      radio: "",
      //弹出框开启状态
      dialogVisible: false,
      // 选中的表单项
      multipleSelection: [],
      // 表格数据
      bookRacks: [],
    };
  },
  created() {
    //TODO:获取远程数据
    selectGroups()
      .then(({ data }) => {
        this.groups = data.data;
        this.zkPath = [1, this.groups[0]];
        this.pitchOn = this.groups[0];
        selectBookRackList(this.groups[0])
          .then(({ data }) => {
            this.bookRacks = data.data;
            console.log("书籍信息", data);
          })
          .catch((err) => {});
      })
      .catch((err) => {});

    this.getBookList(null, null);
  },
};
</script>

<style scoped>
</style>